class Game {
    score = 0;
    land;
    sky;
    bird;
    backgroundTimer = null;
    pipeController = null;
    
    constructor(){
        this.land = new Land();
        this.sky = new Sky();
        this.bird = new Bird();
        this.state = 0;   // 0 遊戲結束  1遊戲開始進行中
        this.init();   
    }

    init(){
        document.onkeydown =  (e) => {
            if((e.key === 'w' || e.key === 'ArrowUp') && this.state === 0){
                console.log('開始遊戲');
                this.state = 1;
                this.startGame();
            }
        }
    }

    startGame(){
        this.pipeController = new GamePipePair(-100);
        if(this.backgroundTimer) return ;
        this.backgroundTimer = setInterval(() => {
            this.land.move(0.01);
            this.sky.move(0.01);
            this.bird.move(0.01);
            this.updateScore();
            if(this.pipeController){
                if(this.pipeController.collisionDetection(this.bird)){
                    this.endGame();
                    console.log('game ended');
                }
            }
        }, 10)


    }

    updateScore(){
        const score = document.querySelector('.score');
        this.score = this.pipeController.getScore(this.bird)
        score.innerHTML = this.score;
    }

    endGame(){
        if(this.backgroundTimer && this.state === 1){
            this.pipeController.stop();
            this.state = 0;
            this.bird.stopSwing();
            clearInterval(this.backgroundTimer);
            this.backgroundTimer = null;
            document.onkeydown = null;
            if(confirm(`游戏结束！！ 
                你最后的得分是${this.score}分
                你想要再玩一局嘛 想玩点确定哦！！！
                `)){
                    this.init();
                }
        }
    }

}

const birdGame = new Game();
